package com.newlink.building.userinfo.activity

import android.content.Intent
import android.net.Uri
import android.os.SystemClock
import android.util.Log
import android.view.View
import android.widget.TextView
import com.alibaba.android.arouter.launcher.ARouter
import com.newlink.building.common_base.base.NL_BaseMvpActivity
import com.newlink.building.common_base.constant.Base_RouterPath
import com.newlink.building.common_base.event.MessageEvent
import com.newlink.building.common_base.event.TYPE_APP_FINISH_FORCE
import com.newlink.building.common_base.ext.showToast
import com.newlink.building.common_base.model.bean.VersionBean
import com.newlink.building.common_base.utils.Base_DeviceUtils
import com.newlink.building.common_base.utils.DialogUtil
import com.newlink.building.common_base.utils.NLog
import com.newlink.building.common_base.utils.checkNewAppVersion
import com.newlink.building.userinfo.BuildConfig
import com.newlink.building.userinfo.R
import com.newlink.building.userinfo.databinding.ActivityAboutBinding
import com.newlink.building.userinfo.mvp.Module_UserInfo_AboutPresenter
import com.newlink.building.userinfo.mvp.contract.Module_UserInfo_AboutContract
import com.newlink.building.userinfo.widget.Module_UserInfo_UpdateDialog
import org.greenrobot.eventbus.EventBus
import org.jetbrains.anko.toast

/**
 * @author wangyang
 * @date 2022/9/20
 * @description 我的——关于页面
 */
class Module_UserInfo_AboutActivityNL : NL_BaseMvpActivity<Module_UserInfo_AboutContract.View, Module_UserInfo_AboutContract.Presenter>(),
    Module_UserInfo_AboutContract.View, View.OnClickListener {

    private var isDevelopModel = false
    private var lastClickTime: Long = 0

    private var mVersionBean: VersionBean? = null

    private val mDialog by lazy {
        DialogUtil.getWaitDialog(this)
    }

    //    override fun attachLayoutRes(): Int {
//        return R.layout.activity_about
//    }
    private lateinit var mBinding: ActivityAboutBinding
    override fun attachLayoutRes(): View {
        mBinding = ActivityAboutBinding.inflate(layoutInflater)
        return mBinding.root
    }

    override fun initData() {
        checkNewAppVersion()
    }

    override fun createPresenter(): Module_UserInfo_AboutContract.Presenter = Module_UserInfo_AboutPresenter()

    val counts: Int = if (BuildConfig.DEBUG) 1 else 5
    val duration: Long = 3 * 1000
    val mHits = LongArray(counts)
    var clickTime = 0

    override fun initView() {
        super.initView()
        findViewById<TextView>(R.id.tv_title_bar_center).text =
            resources.getText(R.string.about)

        mBinding.tvAppVersion.text = String.format(
            resources.getString(R.string.app_version),
            mPresenter?.getCurrentAppVersion(this)
        )

        mBinding.rlVersionUpdate.setOnClickListener(this)

        mBinding.rlVersionUpdate.setOnLongClickListener {
            Log.e("jake", "go permission")

            val intent = Intent(this@Module_UserInfo_AboutActivityNL, Module_UserInfo_PermissionActivityNL::class.java)
            startActivity(intent)
            true
        }

        mBinding.ivAppLogo.setOnClickListener(this)
        mBinding.tvAppName.setOnClickListener(this)
    }

    private var isChecking = false

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.rl_version_update -> {
                //版本更新检测
                val clickTime = System.currentTimeMillis() / 1000
                if (clickTime - lastClickTime < 2) {
                    return
                }
                lastClickTime = clickTime
//                if (isChecking) {
//                    return
//                }
//                isChecking = true
//                checkNewAppVersion()
                NLog.e("2222222222222")
                if (mVersionBean == null) {
                    NLog.e("3333333")
                    checkNewAppVersion()
                } else {
                    NLog.e("net: ${mVersionBean!!.versionCode.toInt()}")
                    NLog.e("current: ${Base_DeviceUtils.getAppVersion(this)}")
                    if (mVersionBean!!.versionCode.toInt() > Base_DeviceUtils.getAppVersion(this)) {
                        NLog.e("1111111111111111")
                        showUpdateDialog(mVersionBean!!)
                    } else {
                        showToast(getString(R.string.update_tips_current_is_newest))
                    }
                }
            }

            R.id.iv_app_logo -> {
                continuousClick()
            }

            R.id.tv_app_name -> {
            }
        }
    }

    private fun checkNewAppVersion() {
        if (isChecking) {
            return
        }
        isChecking = true
        showLoading()
        checkNewAppVersion(accessToken) { versionBean ->
            hideLoading()
            isChecking = false
            if (versionBean != null) {
                NLog.e("versionBean: $versionBean")
                NLog.e("current : ${Base_DeviceUtils.getAppVersion(this)}")
                mVersionBean = versionBean
                updateVersionIcon()
                if (versionBean.versionCode.isNotEmpty()) {
                    if (versionBean.versionCode.toInt() > Base_DeviceUtils.getAppVersion(this)) {
//                        showUpdateDialog(versionBean)
                        NLog.e("---------new Version founded-----------")
                        return@checkNewAppVersion
                    }
                }
            }

        }
    }

    private fun updateVersionIcon() {
        if (mVersionBean != null
            && (mVersionBean?.versionCode?.toInt()!! > Base_DeviceUtils.getAppVersion(this))
        ) {
            NLog.e("---------new Version founded 2-----------")
            mBinding.tvVersionUpdateNeed.visibility = View.VISIBLE
            mBinding.tvVersionUpdateLastest.visibility = View.GONE
        } else {
            NLog.e("---------current Version is latest-----------")
            mBinding.tvVersionUpdateNeed.visibility = View.GONE
            mBinding.tvVersionUpdateLastest.visibility = View.VISIBLE
        }
    }


    private fun continuousClick() {
        /**
         * 实现双击方法
         * src 拷贝的源数组
         * srcPos 从源数组的那个位置开始拷贝.
         * dst 目标数组
         * dstPos 从目标数组的那个位子开始写数据
         * length 拷贝的元素的个数
         */
        System.arraycopy(mHits, 1, mHits, 0, mHits.size - 1)
        //实现左移，然后最后一个位置更新距离开机的时间，如果最后一个时间和最开始时间小于DURATION，即连续5次点击
        mHits[mHits.size - 1] = SystemClock.uptimeMillis()
        clickTime++
        if (mHits[0] >= (SystemClock.uptimeMillis() - duration)) {
            isDevelopModel = true
            val tips = "您已在[" + duration + "]ms内连续点击【" + mHits.size + "】次了！！！"
            Log.e("AboutActivity", "$tips")
//            showToast(tips)
//            ARouter.getInstance().build(RouterPath.PATH_LINPHONE_MAIN).navigation()

            mBinding.ivAppLogo.setOnLongClickListener {
                if (BuildConfig.DEBUG) {
                    if (clickTime % 2 == 1) {
                        startActivity(Intent(this, Module_UserInfo_LogActivityNL::class.java))
                    } else {
                        ARouter.getInstance().build(Base_RouterPath.PATH_LINPHONE_MAIN).navigation()
                    }
                } else {
                    startActivity(Intent(this, Module_UserInfo_LogActivityNL::class.java))
                }
                isDevelopModel = false
                clickTime = 0
                true
            }
        }
    }

    override fun showData() {
    }

    override fun hasNewVersion(bean: VersionBean) {
        mDialog.dismiss()
        Log.e("fvl_dbg", "[about] hasNewVersion --> $bean")
        showUpdateDialog(bean)
    }

    override fun noNewVersion() {
        Log.e("fvl_dbg", "[about] noNewVersion")
        mDialog.dismiss()
        toast(resources.getString(R.string.app_version_update_not_need))
    }

    private fun showUpdateDialog(updateInfo: VersionBean) {
        Module_UserInfo_UpdateDialog.Builder(this)
            .setVersionName(updateInfo.versionName)
            .setUpdateLog(updateInfo.changeLog)
            .setForceUpdate(updateInfo.forceUpdate)
            .setButtonListener(object : Module_UserInfo_UpdateDialog.OnButtonListener {
                override fun onCloseClick() {
                    if (updateInfo.forceUpdate) {
                        this@Module_UserInfo_AboutActivityNL.finish()
                        EventBus.getDefault().post(MessageEvent(TYPE_APP_FINISH_FORCE, true))
                    }
                }

                override fun onUpdateClick() {
                    updateApp()
                }

            })
            .show()
    }


    private fun updateApp() {
        val appPackageName = packageName // Get the package name of the current app
        try {
            startActivity(
                Intent(
                    Intent.ACTION_VIEW,
                    Uri.parse("market://details?id=$appPackageName")
                )
            )
        } catch (e: android.content.ActivityNotFoundException) {
            startActivity(
                Intent(
                    Intent.ACTION_VIEW,
                    Uri.parse("https://play.google.com/store/apps/details?id=$appPackageName")
                )
            )
        }
    }


}